package com.younion.action.manage;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.support.SimpleCacheManager;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.younion.business.ICardCountInitService;
import com.younion.business.ICardEntityService;
import com.younion.business.ICustomerService;
import com.younion.business.IMemberCardCostCountService;
import com.younion.business.IMemberCardService;
import com.younion.business.IMemberCardUpgradeLogService;
import com.younion.business.IMembercardServiceService;
import com.younion.business.IProductService;
import com.younion.business.IRechargeRuleService;
import com.younion.business.IServiceInitService;
import com.younion.business.IUserService;
import com.younion.common.base.BaseAction;
import com.younion.common.constants.RechargeType;
import com.younion.common.constants.TemplateTargetType;
import com.younion.common.exception.BaseException;
import com.younion.common.paginator.Paginator;
import com.younion.permission.PermissionUtil;
import com.younion.util.UUIDUtil;
import com.younion.util.YounionUtil;
import com.younion.vo.CardCountInitVO;
import com.younion.vo.CardEntityVO;
import com.younion.vo.CustomerVO;
import com.younion.vo.MemberCardCostCountVO;
import com.younion.vo.MemberCardUpgradeLogVO;
import com.younion.vo.MemberCardVO;
import com.younion.vo.MembercardServiceVO;
import com.younion.vo.ProductVO;
import com.younion.vo.RechargeLogVO;
import com.younion.vo.RechargeRuleVO;
import com.younion.vo.ServiceInitVO;

import cpcns.jhsks.util.MapCollectionUtils;

/**
 * @author wells
 */
public class MemberCardAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	protected static final Log logger = LogFactory
			.getLog(MemberCardAction.class);

	private IMemberCardService memberCardService = null;

	private IUserService userService = null;

	private MemberCardVO memberCardVO = new MemberCardVO();

	private List<MemberCardVO> memberCardList;// 结果集列表

	private String memberIds;
	
	@Autowired
	private ICustomerService customerService = null;
	
	@Autowired
	private IMemberCardCostCountService memberCardCostCountService = null;
	
//	private Collection products = null;
	private List<RechargeType> rechargeTypeTypes = Arrays.asList(RechargeType.values());
	
	private RechargeLogVO rechargeLog = new RechargeLogVO();
	
	private MemberCardCostCountVO memberCardCostCountVO = new MemberCardCostCountVO();
	
	private String rechargeTargetType;
	@Autowired
	private ICardCountInitService cardCountInitService = null;
	@Autowired
	private IServiceInitService serviceInitService = null;
	@Autowired
	private IMembercardServiceService membercardServiceService = null;
	
	@Autowired
	private IRechargeRuleService rechargeRuleService = null;
	@Autowired
	private ICardEntityService cardEntityService = null;
	@Autowired
	private IMemberCardUpgradeLogService memberCardUpgradeLogService = null;
	
	@Autowired
	private SimpleCacheManager simpleCacheManager = null;
	
	private String searchType;
	/**
	 * 列表：翻页区；数据区
	 */
	@SuppressWarnings("unchecked")
	@RequiresPermissions("listMemberCard")
	public String listMemberCard() {
		try {
			Map paramMap = null;
			CustomerVO customer = getSessionUser().getCustomer();
			Integer userCustomerId = null;
			if (customer != null) {
				userCustomerId = customer.getId();
			}
			if (memberCardVO != null) {
				if (userCustomerId != null) {
					memberCardVO.setCustomerId(userCustomerId);
				}
				paramMap = MapCollectionUtils.removeEmptyEntry(PropertyUtils
						.describe(memberCardVO));
			}
			// 获取总记录数
			int total = memberCardService.getCountByMap(paramMap);
			// 根据总记录数获取分页对象
			Paginator paginator = this.getPaginator(total);
			memberCardList = memberCardService.get(paramMap, paginator);
			//put the params to cache
			simpleCacheManager.getCache(CACHE_KEY).put(getSessionUser().getId(), paramMap);
			// 保存分页对象
			this.savaPaginator(paginator);
			this.addLog(2, "查询会员卡实例列表", "查询会员卡实例列表", this.getSessionUser());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return SUCCESS;
	}

	/**
	 * 新增
	 */
	@RequiresPermissions("addMemberCard")
	public String addMemberCard() {
		return SUCCESS;
	}

	/**
	 * 修改保存，调度Jsp
	 */
	@RequiresPermissions("editMemberCard")
	public String editMemberCard() {
		try {
			memberCardVO = memberCardService.getById(memberCardVO.getId()
					.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 保存动作
	 */
	@RequiresPermissions("saveMemberCard")
	public String saveMemberCard() {
		try {
			if (this.memberCardVO.getId() == null) {
				//check
				Map checkParamMap = Maps.newHashMap();
				checkParamMap.put("userId", memberCardVO.getUserId());
				checkParamMap.put("cardId", memberCardVO.getCardId());
				Collection exists = memberCardService.getByMap(checkParamMap);
				if(exists.size() > 0 ){
					request.setAttribute("dialogId", "sendCardDialog");
					this.tipMessage = "该帐号已发过卡，不能重复发卡！";
					request.setAttribute("callbackType", "forward");
					request.setAttribute("forwardUrl", request.getContextPath()+"/registerUser/listRegisterUser.action");
					return ERROR;
				}
				UUIDUtil UUIDUtil = new UUIDUtil();
				memberCardVO.setSchemeCode(UUIDUtil.getUuid().toString());
				if(memberCardVO.getIsAllowPush()==null)
					memberCardVO.setIsAllowPush(1);
				if(memberCardVO.getIsMobileUser()==null)
					memberCardVO.setIsMobileUser(0);
				if(memberCardVO.getCardBalance()==null)
					memberCardVO.setCardBalance(0.0);
				if(memberCardVO.getScore()==null)
					memberCardVO.setScore(0);
				if(memberCardVO.getHasRecharged()==null)
					memberCardVO.setHasRecharged(0);
				memberCardVO.setAddTime(new Date());
				//发卡有效期类型
				String expiryDateType = request.getParameter("expiryDateType");
				//自选有效期
				if (expiryDateType != null && expiryDateType.equals("0")) {
					Integer year = Integer.parseInt(request.getParameter("year"));
					Integer month = Integer.parseInt(request.getParameter("month"));
					Calendar cal = Calendar.getInstance();
					memberCardVO.setExpiryDateFrom(cal.getTime());
					cal.add(Calendar.YEAR, year);
					cal.add(Calendar.MONTH, month);
					memberCardVO.setExpiryDateTo(cal.getTime());
				}
				//其他
				else {
					//查询出所发的实体卡
					CardEntityVO cardEntityVO = cardEntityService.getById(String.valueOf(memberCardVO.getCardId()));
					//将实体卡有效期带入到实例
					memberCardVO.setExpiryDateFrom(cardEntityVO.getExpiryDateFrom());
					memberCardVO.setExpiryDateTo(cardEntityVO.getExpiryDateTo());
				}
				int memberCardId = memberCardService.saveReturnKey(memberCardVO);
				//发卡成功后需要更新发卡数
				Map updateSendCardAmountParamMap = new HashMap();
				updateSendCardAmountParamMap.put("id", memberCardVO.getCardId());
				updateSendCardAmountParamMap.put("amount", 1);
				cardEntityService.updateSendCardAmountByMap(updateSendCardAmountParamMap);
				memberCardVO.setId(memberCardId);
				//如果是发卡那么就需要将实体卡的初始值带入实例
				Map paramMap = new HashMap();
				paramMap.put("cardEntityId", memberCardVO.getCardId());
				List<CardCountInitVO> cardCountInitList = (List<CardCountInitVO>) cardCountInitService.getByMap(paramMap);
				if(cardCountInitList!=null&&cardCountInitList.size()>0){
					List<MemberCardCostCountVO> memberCardCostCountVOList = new ArrayList();
					for(CardCountInitVO cardCountInitVO : cardCountInitList){
						MemberCardCostCountVO memberCardCostCountVO = new MemberCardCostCountVO();
						memberCardCostCountVO.setCount(cardCountInitVO.getCount());
						memberCardCostCountVO.setMemberCard(memberCardVO);
						memberCardCostCountVO.setProduct(cardCountInitVO.getProductVO());
						memberCardCostCountVOList.add(memberCardCostCountVO);
					}
					memberCardCostCountService.insertVos(memberCardCostCountVOList);
				}
				List<MembercardServiceVO> memberCardService = Lists.newArrayList();
				Collection services = serviceInitService.getByMap(paramMap);
				for (Iterator iter = services.iterator(); iter.hasNext();) {
					ServiceInitVO s = (ServiceInitVO)iter.next();
					MembercardServiceVO membercardServiceVO = new MembercardServiceVO();
					membercardServiceVO.setMemberCard(memberCardVO);
					membercardServiceVO.setMsgType(s.getMsgType());
					membercardServiceVO.setSendTime(s.getSendTime());
					membercardServiceVO.setTemplate(s.getTemplate());
					memberCardService.add(membercardServiceVO);
				}
				membercardServiceService.save(memberCardService);
				MembercardServiceVO service = retreiveMemberCardService(memberCardVO, TemplateTargetType.REGISTER);
				if(service != null){
					String content = YounionUtil.generateMessageContent(service.getTemplate().getContent(), service.getMemberCard());
					sendNotification(service,TemplateTargetType.REGISTER, content);
				}
				this.addLog(3, "发卡："+this.memberCardVO.getCardCode(), "发卡",getSessionUser());
				request.setAttribute("dialogId", "sendCardDialog");
				request.setAttribute("refreshNavTabId", "membercardList");
				request.setAttribute("callbackType", "forward");
				request.setAttribute("forwardUrl", request.getContextPath()+"/registerUser/listRegisterUser.action");
			}else{
				memberCardVO = memberCardService.save(memberCardVO);
				this.addLog(3, "修改会员卡："+this.memberCardVO.getCardCode(), "修改会员卡", getSessionUser());
				request.setAttribute("refreshNavTabId", "membercardList");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 删除
	 */
	@RequiresPermissions("deleteMemberCard")
	public String deleteMemberCard() {
		try {
			String pkId = request.getParameter("selectids");
			List<MemberCardVO> memberCardVOs = memberCardService.selectByIds(Arrays.asList(pkId.split(",")));
			memberCardService.remove(Arrays.asList(pkId.split(",")));
			//删除卡成功后需要更新发卡数
			if(memberCardVOs!=null&&memberCardVOs.size()>0){
				for(MemberCardVO memberCardVO:memberCardVOs){
					Map updateSendCardAmountParamMap = new HashMap();
					updateSendCardAmountParamMap.put("id", memberCardVO.getCardId());
					updateSendCardAmountParamMap.put("amount", -1);
					cardEntityService.updateSendCardAmountByMap(updateSendCardAmountParamMap);
				}
			}
			String log = "删除会员卡实例";
			this.addLog(5, log+pkId, log,getSessionUser());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		request.setAttribute("refreshNavTabId", "membercardList");
		return SUCCESS;
	}

	@RequiresPermissions("sendCard")
	public String sendCard() {
		try {
			String registerInfo = request.getParameter("registerInfo");
			String[] registerInfoArry = registerInfo.split(",");
			request.setAttribute("registerUserId", registerInfoArry[0]);
			request.setAttribute("registerUserName", registerInfoArry[1]);
			request.setAttribute("phone", registerInfoArry[2]);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 查看鿴
	 */
	@RequiresPermissions("viewMemberCard")
	public String viewMemberCard() {
		try {
			memberCardVO = memberCardService.getById(memberCardVO.getId().toString());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return SUCCESS;

	}

	@RequiresPermissions("rechargeCard")
	public String saveRechargeCard() {
		String type = request.getParameter("rechargeTargetType");
		try {
			String memberIds = request.getParameter("memberIds");
			String money = request.getParameter("money");
			List<RechargeLogVO> rechangeLogs = Lists.newArrayList();
			String[] idsArray = memberIds.split(PermissionUtil.comma);
			if("MEMBERCARD".equalsIgnoreCase(type)){
				if(RechargeType.CASH.getName().equals(rechargeLog.getType())){
					rechargeCash(memberIds, money, rechangeLogs, idsArray);
				}else if (RechargeType.COUNT.getName().equals(rechargeLog.getType())){
					rechargeCount(memberIds, rechangeLogs, idsArray);
				}else if (RechargeType.SCORE.getName().equals(rechargeLog.getType())){
					rechargeScore(memberIds, money, rechangeLogs, idsArray);
				}
			}else if("CUSTOMER".equalsIgnoreCase(type)){
				rechargeCustomer(memberIds, money, rechangeLogs, idsArray);
			}
		} catch (Exception e) {
			request.setAttribute("tipMessage", "充值失败");
			e.printStackTrace();
			return ERROR;
		}
		if("MEMBERCARD".equalsIgnoreCase(type)){
			request.setAttribute("refreshNavTabId", "membercardList");
			//request.setAttribute("callbackType", "forward");
			//request.setAttribute("dialogId", "rechargeDialog");
			//request.setAttribute("forwardUrl", request.getContextPath()+"/memberCard/listMemberCard.action");
		}
		else{
			request.setAttribute("refreshNavTabId", "customerList");
			request.setAttribute("callbackType", "forward");
			request.setAttribute("dialogId", "rechargeCusomerDialog");
			request.setAttribute("forwardUrl", request.getContextPath()+"/customer/listCustomer.action");
		}
		return SUCCESS;
	}

	private void rechargeCustomer(String customerIds, String money,
			List<RechargeLogVO> rechangeLogs, String[] idsArray)
			throws Exception {
		if (StringUtils.isNotBlank(customerIds)
				&& StringUtils.isNotBlank(money)) {
			Map map = Maps.newHashMap();
			List<Integer> ids = Lists.newArrayList();
			map.put("money", Double.valueOf(money));
			for (String id : idsArray) {
				ids.add(Integer.valueOf(id));
				RechargeLogVO log = new RechargeLogVO();
				log.setType("CUSTOMER");
				log.setMoney(Double.valueOf(money));
				log.setCreateDate(new Date());
				log.setCustomer(new CustomerVO(Integer.valueOf(id)));
				log.setDescription(rechargeLog.getDescription());
				log.setOperator(getSessionUser());
				rechangeLogs.add(log);
				this.addLog(3, "商家充值：商家ID["+id+"],充值"+money+"元" , "商家充值", getSessionUser());
			}
			map.put("ids", ids);
			customerService.updateCustomerMoney(map, rechangeLogs);
		}
	}
	
	private void rechargeCash(String memberIds, String money,
			List<RechargeLogVO> rechangeLogs, String[] idsArray)
			throws Exception {
		if (StringUtils.isNotBlank(memberIds)
				&& StringUtils.isNotBlank(money)) {
			List<Map<String,Object>> cardParams = Lists.newArrayList();
			Map<MemberCardVO, Map> cards = Maps.newHashMap();
			for (String id : idsArray) {
				String description = rechargeLog.getDescription();
				Map map = Maps.newHashMap();
				Double inputMoney = Double.valueOf(money);
				Double realMoney = inputMoney;
				Integer realPoint = 0;
				MemberCardVO card = memberCardService.getById(id);
				//第一次充值
				if(card.getHasRecharged() == null || card.getHasRecharged() == 0){
					RechargeRuleVO rule = rechargeRuleService.getByMemberCardId(card.getCardId(),  inputMoney);
					if(rule != null){
						realMoney += rule.getFirstGiveMoney();
						realPoint += rule.getGivePoint();
						map.put("firedRuleId", rule.getId());
						map.put("feedBackCount", 0);
						description = description+" 首次充值,"+rule.getTitle();
					}
					map.put("hasRecharged", 1);
				}
				map.put("money", realMoney);
				map.put("score", realPoint);
				map.put("ids", id);
				cardParams.add(map);
				RechargeLogVO log = new RechargeLogVO();
				log.setType(rechargeLog.getType());
				log.setMoney(realMoney);
				log.setCreateDate(new Date());
				log.setMembercard(new MemberCardVO(Integer.valueOf(id)));
				log.setOperator(getSessionUser());
				log.setCustomer(new CustomerVO(card.getCustomerId()));
				log.setDescription(description);
				rechangeLogs.add(log);
				cards.put(card, map);
				this.addLog(3, "会员卡现金充值："+card.getCardCode()+",充值"+inputMoney+"元" , "会员卡", getSessionUser());
			}
			memberCardService.updateMemberCardMoney(cardParams, rechangeLogs);
			
			// 通知
			for(MemberCardVO card : cards.keySet()){
				Map map = cards.get(card);
				MembercardServiceVO service = retreiveMemberCardService(card, TemplateTargetType.RECHARGE);
				if(service != null){
					String content = YounionUtil.generateMessageContent(service.getTemplate().getContent(), service.getMemberCard());
					content = YounionUtil.generateChangeData(content, null, null, 
							Integer.valueOf(map.get("score").toString()), null, null,
							Double.valueOf(map.get("money").toString()),null);
					sendNotification(service,TemplateTargetType.RECHARGE, content);
				}
			}
		}
	}
	
	private void rechargeScore(String memberIds, String money,
			List<RechargeLogVO> rechangeLogs, String[] idsArray)
	throws Exception {
		if (StringUtils.isNotBlank(memberIds)
				&& StringUtils.isNotBlank(money)) {
			List<Map<String,Object>> cardParams = Lists.newArrayList();
			Map<MemberCardVO, Map> cards = Maps.newHashMap();
			for (String id : idsArray) {
				Map map = Maps.newHashMap();
				map.put("score", Integer.valueOf(money));
				map.put("ids", id);
				cardParams.add(map);
				MemberCardVO card = memberCardService.getById(id);
				RechargeLogVO log = new RechargeLogVO();
				log.setType(rechargeLog.getType());
				log.setMoney(Double.valueOf(money));
				log.setCreateDate(new Date());
				log.setMembercard(new MemberCardVO(Integer.valueOf(id)));
				log.setDescription(rechargeLog.getDescription());
				log.setOperator(getSessionUser());
				log.setCustomer(new CustomerVO(card.getCustomerId()));
				rechangeLogs.add(log);
				cards.put(card, map);
				this.addLog(3, "会员卡积分充值：会员卡ID["+ id +"],充值"+money+"分" , "会员卡积分充值", getSessionUser());
			}
			memberCardService.updateMemberCardMoney(cardParams, rechangeLogs);
			// 通知
			for(MemberCardVO card : cards.keySet()){
				Map map = cards.get(card);
				MembercardServiceVO service = retreiveMemberCardService(card, TemplateTargetType.SCORE);
				if(service != null){
					String content = YounionUtil.generateMessageContent(service.getTemplate().getContent(), service.getMemberCard());
					content = YounionUtil.generateChangeData(content, null, null, 
							Integer.valueOf(map.get("score").toString()), null, null, null,null);
					sendNotification(service,TemplateTargetType.SCORE, content);
				}
			}
		}
	}

	private void rechargeCount(String memberIds,
			List<RechargeLogVO> rechangeLogs, String[] idsArray)
			throws Exception {
		if (StringUtils.isNotBlank(memberIds)
				&& StringUtils.isNotBlank(memberCardCostCountVO.getCount().toString())) {
			List<Integer> ids = Lists.newArrayList();
			List<MemberCardCostCountVO> updateCounts = Lists.newArrayList();
			Map<MemberCardVO, MemberCardCostCountVO> cards = Maps.newHashMap();
			for (String id : idsArray) {
				ids.add(Integer.valueOf(id));
				RechargeLogVO log = new RechargeLogVO();
				log.setType(rechargeLog.getType());
				log.setCount(memberCardCostCountVO.getCount());
				log.setProduct(new ProductVO(memberCardCostCountVO.getProductId()));
				log.setCreateDate(new Date());
				log.setMembercard(new MemberCardVO(Integer.valueOf(id)));
				log.setOperator(getSessionUser());
				MemberCardVO card = memberCardService.getById(id);
				log.setCustomer(new CustomerVO(card.getCustomerId()));
				rechangeLogs.add(log);
				MemberCardCostCountVO m = fetchDBObj(memberCardCostCountVO.getProductId(), Integer.valueOf(id));
				if(m == null){
					MemberCardCostCountVO newMemberCardCostCount = new MemberCardCostCountVO();
					newMemberCardCostCount.setCount(memberCardCostCountVO.getCount());
					newMemberCardCostCount.setMemberCard(new MemberCardVO(Integer.valueOf(id)) );
					newMemberCardCostCount.setProduct(new ProductVO(memberCardCostCountVO.getProductId()));
					updateCounts.add(newMemberCardCostCount);
				}else{
					m.setCount(m.getCount() + memberCardCostCountVO.getCount());
					updateCounts.add(m);
				}
				cards.put(card, m);
				this.addLog(3, "会员卡次数充值：会员卡ID["+ id +"],充值"+memberCardCostCountVO.getCount()+"次" , "会员卡次数充值", getSessionUser());
			}
			memberCardCostCountService.save(updateCounts, rechangeLogs);
			
			// 通知
			for(MemberCardVO card : cards.keySet()){
				MemberCardCostCountVO m = cards.get(card);
				MembercardServiceVO service = retreiveMemberCardService(card, TemplateTargetType.ADDCOUNT);
				if(service != null){
					String content = YounionUtil.generateMessageContent(service.getTemplate().getContent(), service.getMemberCard());
					content = YounionUtil.generateMessageContentByMembercardCostCount(content, m);
					content = YounionUtil.generateChangeData(content, memberCardCostCountVO.getCount(), null, null, null, m.getCount(), null,null);
					if( m.getProductName() != null){
						content = YounionUtil.generateMessageContentByProduct(content, m.getProductName());
					}
					sendNotification(service,TemplateTargetType.ADDCOUNT, content);
				}
			}
		}
	}

	private MemberCardCostCountVO fetchDBObj(Integer productId, Integer memberId){
		Map paramMap = Maps.newHashMap();
		paramMap.put("productId", productId);
		paramMap.put("memberCardId", memberId);
		try {
			Collection l = memberCardCostCountService.getByMap(paramMap);
			Iterator it = l.iterator();
			while(it.hasNext()){
				return (MemberCardCostCountVO)it.next();
			}
		} catch (BaseException e) {
			return null;
		}
		return null;
	}
	
	@RequiresPermissions("rechargeCard")
	public String rechargeCard() {
		try {
			String pkId = request.getParameter("ids");
			rechargeTargetType = request.getParameter("type");
			memberIds = pkId == null ? "" : pkId
					.substring(0, pkId.length() - 1);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	@RequiresPermissions("deferMemberCard")
	public String deferMemberCard() {
		Integer type = Integer.valueOf(request.getParameter("deferType"));
		//按月延期
		if (type == 0) {
			Integer month = Integer.valueOf(request.getParameter("deferMonth"));
			if(this.memberCardVO.getExpiryDateTo()==null)
				this.memberCardVO.setExpiryDateTo(new Date());
			Calendar cal = Calendar.getInstance();
			cal.setTime(this.memberCardVO.getExpiryDateTo());
			cal.add(Calendar.MONTH, month);
			this.memberCardVO.setExpiryDateTo(cal.getTime());
		} else {
			String deferDate = request.getParameter("deferDate");
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			try {
				this.memberCardVO.setExpiryDateTo(df.parse(deferDate));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		try {
			this.memberCardService.save(memberCardVO);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	@RequiresPermissions("upgradeMemberCard")
	public String upgradeMemberCard() {
		try {
			MemberCardVO mc = this.memberCardService.getById(String.valueOf(this.memberCardVO.getId()));
			CardEntityVO ce = this.cardEntityService.getById(String.valueOf(mc.getCardId()));
			CustomerVO cust = this.customerService.getById(String.valueOf(mc.getCustomerId()));
			CardEntityVO newCE = this.cardEntityService.getById(String.valueOf(this.memberCardVO.getCardId()));
			String temp = "商家【"+cust.getName()+"】的会员卡【"+mc.getSchemeCode()+"："+(mc.getMemberName()==null?"":mc.getMemberName())+"】由【级别为：["+ce.getCardLevelVO().getLevelName()+"："+ce.getCardLevelVO().getLevel()+"]的会员卡："+ce.getCardName()+"】更换为【级别为：["+newCE.getCardLevelVO().getLevelName()+"："+newCE.getCardLevelVO().getLevel()+"]的会员卡："+newCE.getCardName()+"】";
			MemberCardUpgradeLogVO mcul = new MemberCardUpgradeLogVO();
			mcul.setMemberCardId(mc.getId());
			mcul.setCustomerId(mc.getCustomerId());
			mcul.setUserId(mc.getUserId());
			mcul.setOldCardId(ce.getId());
			mcul.setNewCardId(newCE.getId());
			mcul.setOperUserId(this.getSessionUser().getId());
			mcul.setRemark(temp);
			this.memberCardVO.setCardCode(ce.getSchemeCode());
			this.memberCardService.save(this.memberCardVO);
			this.memberCardUpgradeLogService.insertByVo(mcul);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return SUCCESS;
	}

	public MemberCardVO getMemberCardVO() {
		return memberCardVO;
	}

	public void setMemberCardVO(MemberCardVO memberCardVO) {
		this.memberCardVO = memberCardVO;
	}

	public void setMemberCardService(IMemberCardService memberCardService) {
		this.memberCardService = memberCardService;
	}

	public List<MemberCardVO> getMemberCardList() {
		return memberCardList;
	}

	public void setMemberCardList(List<MemberCardVO> memberCardList) {
		this.memberCardList = memberCardList;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public String getMemberIds() {
		return memberIds;
	}

	public void setMemberIds(String memberIds) {
		this.memberIds = memberIds;
	}

	public IMemberCardService getMemberCardService() {
		return memberCardService;
	}
/*	
	public Collection getProducts() {
		if(products == null){
			try {
				products = productService.getAll();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return products;
	}

	public void setProducts(Collection products) {
		this.products = products;
	}
*/
	public IProductService getProductService() {
		return productService;
	}

	public void setProductService(IProductService productService) {
		this.productService = productService;
	}

	public List<RechargeType> getRechargeTypeTypes() {
		return rechargeTypeTypes;
	}

	public void setRechargeTypeTypes(List<RechargeType> rechargeTypeTypes) {
		this.rechargeTypeTypes = rechargeTypeTypes;
	}

	public IUserService getUserService() {
		return userService;
	}

	public IMemberCardCostCountService getMemberCardCostCountService() {
		return memberCardCostCountService;
	}

	public void setMemberCardCostCountService(
			IMemberCardCostCountService memberCardCostCountService) {
		this.memberCardCostCountService = memberCardCostCountService;
	}


	public RechargeLogVO getRechargeLog() {
		return rechargeLog;
	}

	public void setRechargeLog(RechargeLogVO rechargeLog) {
		this.rechargeLog = rechargeLog;
	}

	public MemberCardCostCountVO getMemberCardCostCountVO() {
		return memberCardCostCountVO;
	}

	public void setMemberCardCostCountVO(MemberCardCostCountVO memberCardCostCountVO) {
		this.memberCardCostCountVO = memberCardCostCountVO;
	}

	public String getRechargeTargetType() {
		return rechargeTargetType;
	}

	public void setRechargeTargetType(String rechargeTargetType) {
		this.rechargeTargetType = rechargeTargetType;
	}

	public ICustomerService getCustomerService() {
		return customerService;
	}

	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}

	public void setCardCountInitService(ICardCountInitService cardCountInitService) {
		this.cardCountInitService = cardCountInitService;
	}

	public void setServiceInitService(IServiceInitService serviceInitService) {
		this.serviceInitService = serviceInitService;
	}

	public void setMembercardServiceService(
			IMembercardServiceService membercardServiceService) {
		this.membercardServiceService = membercardServiceService;
	}

	public IRechargeRuleService getRechargeRuleService() {
		return rechargeRuleService;
	}

	public void setRechargeRuleService(IRechargeRuleService rechargeRuleService) {
		this.rechargeRuleService = rechargeRuleService;
	}

	public ICardCountInitService getCardCountInitService() {
		return cardCountInitService;
	}

	public IServiceInitService getServiceInitService() {
		return serviceInitService;
	}

	public IMembercardServiceService getMembercardServiceService() {
		return membercardServiceService;
	}

	public ICardEntityService getCardEntityService() {
		return cardEntityService;
	}

	public void setCardEntityService(ICardEntityService cardEntityService) {
		this.cardEntityService = cardEntityService;
	}

	public void setMemberCardUpgradeLogService(
			IMemberCardUpgradeLogService memberCardUpgradeLogService) {
		this.memberCardUpgradeLogService = memberCardUpgradeLogService;
	}

	public SimpleCacheManager getSimpleCacheManager() {
		return simpleCacheManager;
	}

	public void setSimpleCacheManager(SimpleCacheManager simpleCacheManager) {
		this.simpleCacheManager = simpleCacheManager;
	}

	public String getSearchType() {
		return searchType;
	}

	public void setSearchType(String searchType) {
		this.searchType = searchType;
	}
	
}